package com.bsg.upm.service;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsg.upm.constant.DictConstants;
import com.bsg.upm.constant.SysConstants;
import com.bsg.upm.dao.ClusterDao;
import com.bsg.upm.dao.HostDao;
import com.bsg.upm.dao.MonitorEventDao;
import com.bsg.upm.dao.MonitorResourceDao;
import com.bsg.upm.dao.OrderDao;
import com.bsg.upm.dao.PortDao;
import com.bsg.upm.dao.ServDao;
import com.bsg.upm.entity.ClusterEntity;
import com.bsg.upm.entity.MonitorResourceEntity;
import com.bsg.upm.entity.OrderEntity;
import com.bsg.upm.entity.PortEntity;
import com.bsg.upm.entity.ServEntity;
import com.bsg.upm.entity.SubServEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;

/**
 * 
 * @author yucs
 *
 */

@Service
public class DashboardService extends BaseService {
	@Resource
	private OrderDao orderDao;

	@Resource
	private ClusterDao clusterDao;

	@Resource
	private HostDao hostDao;

	@Resource
	private PortDao portDao;

	@Resource
	private ServDao servDao;

	@Resource
	private MonitorResourceDao monitorResourceDao;
	@Resource
	private MonitorSubServService monitorSubServService;
	@Resource
	private SubServService subServService;

	@Resource
	private MonitorEventDao monitorEventDao;

	public RespJson getOrderStatus(String siteId) throws APIException {
		try {

			Map<String, Integer> maps = new HashMap<String, Integer>();

			maps.put(DictConstants.ORDER_STATUS_APPROVED, 0);
			maps.put(DictConstants.ORDER_STATUS_EXECUTED, 0);

			maps.put(DictConstants.ORDER_STATUS_UNAPPROVED, 0);
			maps.put(DictConstants.ORDER_STATUS_UNAPPROVE, 0);

			List<OrderEntity> orders = orderDao.listAllBySiteID(siteId);
			for (OrderEntity order : orders) {
				maps.put(order.getStatus(), maps.get(order.getStatus()) + 1);
			}

			return RespJsonFactory.buildOK(maps);
		} catch (Exception e) {
			logger.error("getOrderStatus fail:", e);
			throw new APIException("getOrderStatus fail:" + e.getMessage());
		}
	}

	public RespJson getServStatus(String siteId) throws APIException {
		try {

			Map<String, Integer> maps = new HashMap<String, Integer>();
			maps.put(DictConstants.SUBSERV_STATUS_CRITICAL, 0);
			maps.put(DictConstants.SUBSERV_STATUS_PASSING, 0);
			maps.put(DictConstants.SUBSERV_STATUS_UNKNOWN, 0);
			maps.put(DictConstants.SUBSERV_STATUS_WARNNING, 0);

			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("siteId", siteId);
			List<ServEntity> servList = servDao.list(paramMap);
			if (servList.isEmpty()) {
				return RespJsonFactory.buildOK(maps);
			}

			Map<String, JSONArray> servMap = monitorSubServService.getAllUnitMonitorStatusJsonArrMap(siteId);

			for (ServEntity serv : servList) {
				int unit_num = 0;
				JSONArray servArr = new JSONArray();
				boolean allFindFromHS = true;

				for (SubServEntity subServ : serv.getSubServs()) {

					unit_num += subServ.getSubOrder().getDefinitionSubServArch().getUnitNum();
					if (!servMap.containsKey(subServ.getRelateId())) {
						allFindFromHS = false;
						break;
					}
					servArr.addAll(servMap.get(subServ.getRelateId()));
				}

				if (!allFindFromHS) {
					maps.put(DictConstants.SUBSERV_STATUS_WARNNING,
							maps.get(DictConstants.SUBSERV_STATUS_WARNNING) + 1);
				} else {
					String status = subServService.getSubServStatus(unit_num, servArr);
					maps.put(status, maps.get(status) + 1);
				}

			}

			return RespJsonFactory.buildOK(maps);

		} catch (Exception e) {
			logger.error("getServStatus fail:", e);
			throw new APIException("getServStatus fail:" + e.getMessage());
		}
	}

	public RespJson getSubServStatus(String siteId) throws APIException {
		try {

			Map<String, Integer> maps = new HashMap<String, Integer>();
			maps.put(DictConstants.SUBSERV_STATUS_CRITICAL, 0);
			maps.put(DictConstants.SUBSERV_STATUS_PASSING, 0);
			maps.put(DictConstants.SUBSERV_STATUS_UNKNOWN, 0);
			maps.put(DictConstants.SUBSERV_STATUS_WARNNING, 0);

			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("siteId", siteId);
			List<ServEntity> servList = servDao.list(paramMap);
			if (servList.isEmpty()) {
				return RespJsonFactory.buildOK(maps);
			}

			Map<String, JSONArray> servMap = monitorSubServService.getAllUnitMonitorStatusJsonArrMap(siteId);

			for (ServEntity serv : servList) {
				for (SubServEntity subServ : serv.getSubServs()) {

					int unit_num = subServ.getSubOrder().getDefinitionSubServArch().getUnitNum();

					if (!servMap.containsKey(subServ.getRelateId())) {
						maps.put(DictConstants.SUBSERV_STATUS_WARNNING,
								maps.get(DictConstants.SUBSERV_STATUS_WARNNING) + 1);
						continue;
					}

					JSONArray servArr = servMap.get(subServ.getRelateId());
					String status = subServService.getSubServStatus(unit_num, servArr);
					maps.put(status, maps.get(status) + 1);

				}
			}

			return RespJsonFactory.buildOK(maps);

		} catch (Exception e) {
			logger.error("getSubServStatus fail:", e);
			throw new APIException("getSubServStatus fail:" + e.getMessage());
		}
	}

	public RespJson getSiteInfo(String siteId) throws APIException {
		try {
			JSONObject ret = new JSONObject();

			ret.put("networking", getSiteNetWorkingInfo(siteId));
			ret.put("port", getSitePortInfo(siteId));
			ret.put("service", getSiteServInfo(siteId));

			return RespJsonFactory.buildOK(ret);

		} catch (Exception e) {
			logger.error("getSiteInfo fail:", e);
			throw new APIException("getSiteInfo fail:" + e.getMessage());
		}
	}

	public RespJson getMonotorAlarmResource(String siteId) throws APIException {
		try {
			int nosend = monitorEventDao.countAlarm(false, siteId);
			int sended = monitorEventDao.countAlarm(true, siteId);

			JSONObject ret = new JSONObject();
			ret.put("alarm_sended", sended);
			ret.put("alarm_nosend", nosend);

			return RespJsonFactory.buildOK(ret);
		} catch (Exception e) {
			logger.error("getMonotorAlarmResource fail:", e);
			throw new APIException("getMonotorAlarmResource fail:" + e.getMessage());
		}
	}

	public RespJson getMonitorResource(String siteId) throws APIException {
		try {
			int num = 25;
			JSONArray retJsonArray = new JSONArray();

			Long hour = new Long(60 * 60 * 1000);
			Long start = System.currentTimeMillis() / hour * hour - hour;
			Map<Long, MonitorResourceEntity> maps = getMonitorResourceMap(siteId, start - num * hour);

			for (int i = 0; i < num; i++) {
				JSONObject object = new JSONObject();
				Long time = start - i * hour;

				object.put("timestamp", time);
				object.put("containerCnt", null);
				object.put("hostCnt", null);

				if (maps.containsKey(time)) {
					MonitorResourceEntity data = maps.get(time);

					object.put("containerCnt", data.getContainerCnt());
					object.put("hostCnt", data.getHostCnt());

				}

				retJsonArray.add(object);
			}

			return RespJsonFactory.buildOK(retJsonArray);

		} catch (Exception e) {

			logger.error("getMonitorResource fail:", e);
			throw new APIException("getMonitorResource fail:" + e.getMessage());
		}
	}

	private JSONArray getNetWorkInfoFromMGM(String siteId) throws APIException {
		String urlPattern = "/{0}/networkings";
		String url = MessageFormat.format(urlPattern, SysConstants.MGM_VERSION);
		RespJson httpRespJson = sendHttpGet(siteId, SysConstants.INTERFACE_TYPE_MGM, url);
		if (httpRespJson.getStatus() == HttpStatus.SC_OK) {
			return ((JSONArray) httpRespJson.getData());
		} else {
			throw new APIException(httpRespJson.getMsg());
		}
	}

	private Map<Long, MonitorResourceEntity> getMonitorResourceMap(String siteId, Long timeStamp) {

		Map<Long, MonitorResourceEntity> maps = new HashMap<Long, MonitorResourceEntity>();

		List<MonitorResourceEntity> datas = monitorResourceDao.listByTimestampAndSiteId(timeStamp, siteId);

		for (MonitorResourceEntity data : datas) {
			maps.put(data.getTimestamp(), data);
		}

		return maps;
	}

	private JSONObject getSitePortInfo(String siteId) {
		JSONObject retInfo = new JSONObject();

		List<PortEntity> unused = portDao.listUnused(siteId);
		int all = portDao.countPort(siteId, 0, 999999);

		retInfo.put("used", all - unused.size());
		retInfo.put("all", all);

		return retInfo;

	}

	private JSONObject getSiteServInfo(String siteId) throws APIException {
		JSONObject retInfo = new JSONObject();
		int all = servDao.countBySiteId(siteId);
		retInfo.put("all", all);
		return retInfo;
	}

	private JSONObject getSiteNetWorkingInfo(String siteId) throws APIException {
		JSONArray Infos = getNetWorkInfoFromMGM(siteId);

		JSONObject retInfo = new JSONObject();
		int usedCount = 0;
		int allCount = 0;
		for (Object tmp : Infos) {
			JSONObject netwokings = (JSONObject) tmp;
			JSONArray ips = netwokings.getJSONArray("IPs");

			allCount += ips.size();

			for (Object ip : ips) {
				JSONObject ipObj = (JSONObject) ip;
				if (!ipObj.getString("unit_id").equals("")) {
					usedCount += 1;
				}
			}

		}

		retInfo.put("all", allCount);
		retInfo.put("used", usedCount);

		return retInfo;
	}

	public RespJson getClusterInfo(String clusterId) throws APIException {
		try {
			JSONObject ret = new JSONObject();

			ClusterEntity cluster = clusterDao.get(clusterId);
			if (cluster == null) {
				return RespJsonFactory.build(HttpStatus.SC_GONE, "该集群不存在");
			}

			String siteId = cluster.getArea().getSite().getId();
			String relateClusterId = cluster.getRelateId();

			JSONArray mgmHostInfos = listHostInfoFromMGM(siteId, relateClusterId);
			Map<String, Object> clusterInfos = mergeClusterInfo(mgmHostInfos);

			ret.put("cpu_all", clusterInfos.get(relateClusterId + "cpu_all"));
			ret.put("cpu_free", clusterInfos.get(relateClusterId + "cpu_free"));

			ret.put("memory_free", clusterInfos.get(relateClusterId + "memory_free"));
			ret.put("memory_all", clusterInfos.get(relateClusterId + "memory_all"));

			ret.put("hostCnt", clusterInfos.get(relateClusterId + "hostCnt"));
			ret.put("containerCnt", clusterInfos.get(relateClusterId + "containerCnt"));

			ret.put("volume_all", clusterInfos.get(relateClusterId + "volume_all"));
			ret.put("volume_free", clusterInfos.get(relateClusterId + "volume_free"));

			return RespJsonFactory.buildOK(ret);

		} catch (Exception e) {
			logger.error("主页获取集群主机信息异常", e);
			throw new APIException("主页获取集群主机信息异常" + e.getMessage());

		}

	}

	private Map<String, Object> mergeClusterInfo(JSONArray mgmHostInfos) {
		Map<String, Object> maps = new HashMap<String, Object>();

		for (Object tmp : mgmHostInfos) {

			JSONObject host = (JSONObject) tmp;
			String clusterId = host.getString("cluster_id");

			String cpuAllkey = clusterId + "cpu_all";
			if (!maps.containsKey(cpuAllkey)) {
				maps.put(cpuAllkey, new Integer(0));
			}
			maps.put(cpuAllkey, (Integer) maps.get(cpuAllkey) + host.getJSONObject("Engine").getInteger("cpus"));

			String cpuFreeKey = clusterId + "cpu_free";
			if (!maps.containsKey(cpuFreeKey)) {
				maps.put(cpuFreeKey, new Integer(0));
			}
			maps.put(cpuFreeKey, (Integer) maps.get(cpuFreeKey) + host.getJSONObject("Engine").getInteger("free_cpus"));

			String memAllkey = clusterId + "memory_all";
			if (!maps.containsKey(memAllkey)) {
				maps.put(memAllkey, new Long(0));
			}
			maps.put(memAllkey, (Long) maps.get(memAllkey) + host.getJSONObject("Engine").getLong("memory"));

			String memFreekey = clusterId + "memory_free";
			if (!maps.containsKey(memFreekey)) {
				maps.put(memFreekey, new Long(0));
			}
			maps.put(memFreekey, (Long) maps.get(memFreekey) + host.getJSONObject("Engine").getLong("free_memory"));

			String hostkey = clusterId + "hostCnt";
			if (!maps.containsKey(hostkey)) {
				maps.put(hostkey, new Long(0));
			}
			maps.put(hostkey, (Long) maps.get(hostkey) + 1);

			JSONArray volume_drivers = host.getJSONArray("volume_drivers");
			String volumetotalkey = clusterId + "volume_all";
			if (!maps.containsKey(volumetotalkey)) {
				maps.put(volumetotalkey, new Long(0));
			}
			String volumefreekey = clusterId + "volume_free";
			if (!maps.containsKey(volumefreekey)) {
				maps.put(volumefreekey, new Long(0));
			}

			for (Object temp : volume_drivers) {
				JSONObject volume = (JSONObject) temp;
				maps.put(volumetotalkey, (Long) maps.get(volumetotalkey) + volume.getLong("total"));
				maps.put(volumefreekey, (Long) maps.get(volumefreekey) + volume.getLong("free"));

			}

			String contaierkey = clusterId + "containerCnt";
			if (!maps.containsKey(contaierkey)) {
				maps.put(contaierkey, new Long(0));
			}
			maps.put(contaierkey, (Long) maps.get(contaierkey) + (host.getJSONArray("containers")).size());
		}

		return maps;
	}

	private JSONArray listHostInfoFromMGM(String siteId, String clusterId) throws APIException {
		String urlPattern = "/{0}/hosts?cluster={1}";
		String url = MessageFormat.format(urlPattern, SysConstants.MGM_VERSION, clusterId);
		RespJson httpRespJson = sendHttpGet(siteId, SysConstants.INTERFACE_TYPE_MGM, url);
		if (httpRespJson.getStatus() == HttpStatus.SC_OK) {
			return ((JSONArray) httpRespJson.getData());
		} else {
			throw new APIException(httpRespJson.getMsg());
		}
	}

	// @Resource
	// private OrderDao orderDao;
	//
	// @Resource
	// private ClusterDao clusterDao;
	//
	// @Resource
	// private HostContainerCntDao hostContainerCntDao;
	//
	// @Resource
	// private ServDao servDao;
	//
	// @Resource
	// private ServService servService;
	//
	// public RespJson getOrderStatus(HttpServletRequest request, Map<String,
	// Object> param) throws APIException {
	// try {
	// String siteId = (String) param.get("siteId");
	// List<OrderEntity> orders = orderDao.listOrderStatusBySiteId(siteId);
	// int unapprovedCnt = 0;
	// int approvedCnt = 0;
	// int unapproveCnt = 0;
	// int executeRunningCnt = 0;
	// int executeSuccessCnt = 0;
	// int executeFailureCnt = 0;
	// for (OrderEntity order : orders) {
	// if (order.getStatus().equals(DictConstants.ORDER_STATUS_UNAPPROVED)) {
	// unapprovedCnt++;
	// } else if (order.getStatus().equals(DictConstants.ORDER_STATUS_APPROVED))
	// {
	// approvedCnt++;
	// } else if
	// (order.getStatus().equals(DictConstants.ORDER_STATUS_UNAPPROVE)) {
	// unapproveCnt++;
	// } else if
	// (order.getStatus().equals(DictConstants.ORDER_STATUS_EXECUTE_RUNNING)) {
	// executeRunningCnt++;
	// } else if
	// (order.getStatus().equals(DictConstants.ORDER_STATUS_EXECUTE_SUCCESS)) {
	// executeSuccessCnt++;
	// } else if
	// (order.getStatus().equals(DictConstants.ORDER_STATUS_EXECUTE_FAILURE)) {
	// executeFailureCnt++;
	// }
	// }
	// JSONObject statusJson = new JSONObject();
	// statusJson.put("unapprovedCnt", unapprovedCnt);
	// statusJson.put("approvedCnt", approvedCnt);
	// statusJson.put("unapproveCnt", unapproveCnt);
	// statusJson.put("executeRunningCnt", executeRunningCnt);
	// statusJson.put("executeSuccessCnt", executeSuccessCnt);
	// statusJson.put("executeFailureCnt", executeFailureCnt);
	// return RespJsonFactory.buildOK(statusJson);
	// } catch (Exception e) {
	// logger.error("工单状态查询异常", e);
	// throw new APIException("工单状态查询异常:" + e.getMessage());
	// }
	// }
	//
	// public RespJson getResourcesUsed(HttpServletRequest request, Map<String,
	// Object> param) throws APIException {
	// try {
	// Date nowDate = new Date();
	// Calendar c = Calendar.getInstance();
	// c.setTime(nowDate);
	// c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - 30);
	// param.put("timestampStart", c.getTime());
	// param.put("timestampEnd", nowDate);
	// List<HostContainerCntEntity> hostContainerCnts =
	// hostContainerCntDao.list(param);
	// JSONArray hostUsedJsonArr = new JSONArray();
	// JSONArray containerUsedJsonArr = new JSONArray();
	// JSONArray warningJsonArr = new JSONArray();
	// for (HostContainerCntEntity hostContainerCnt : hostContainerCnts) {
	// JSONObject hostUsedJson = new JSONObject();
	// hostUsedJson.put("timestamp", hostContainerCnt.getTimestamp().getTime());
	// hostUsedJson.put("value", hostContainerCnt.getHostCnt());
	// hostUsedJsonArr.add(hostUsedJson);
	//
	// JSONObject containerUsedJson = new JSONObject();
	// containerUsedJson.put("timestamp",
	// hostContainerCnt.getTimestamp().getTime());
	// containerUsedJson.put("value", hostContainerCnt.getContainerCnt());
	// containerUsedJsonArr.add(containerUsedJson);
	//
	// JSONObject warningJson = new JSONObject();
	// warningJson.put("timestamp", hostContainerCnt.getTimestamp().getTime());
	// warningJson.put("value", hostContainerCnt.getHostCnt() * 8);
	// warningJsonArr.add(warningJson);
	// }
	// JSONObject resourcesUsedJson = new JSONObject();
	// resourcesUsedJson.put("hostUsed", hostUsedJsonArr);
	// resourcesUsedJson.put("containerUsed", containerUsedJsonArr);
	// resourcesUsedJson.put("warning", warningJsonArr);
	// return RespJsonFactory.buildOK(resourcesUsedJson);
	// } catch (Exception e) {
	// logger.error("资源使用趋势查询异常", e);
	// throw new APIException("资源使用趋势查询异常:" + e.getMessage());
	// }
	// }
	//
	// public RespJson getClusterResourcesAllocation(HttpServletRequest request,
	// Map<String, Object> param)
	// throws APIException {
	// try {
	// String clusterId = (String) param.get("clusterId");
	// ClusterEntity cluster = clusterDao.get(clusterId);
	// if (cluster == null) {
	// return RespJsonFactory.build(HttpStatus.SC_GONE, "该集群不存在");
	// }
	// String siteId = cluster.getArea().getSite().getId();
	//
	// JSONObject json = new JSONObject();
	// JSONObject cpuJson = new JSONObject();
	// JSONObject memJson = new JSONObject();
	// JSONObject diskJson = new JSONObject();
	// JSONObject containerJson = new JSONObject();
	// json.put("cpu", cpuJson);
	// json.put("mem", memJson);
	// json.put("disk", diskJson);
	// json.put("container", containerJson);
	//
	// int cpuSum = 0;
	// int cpuUsed = 0;
	// long memSumSize = 0;
	// long memUsedSize = 0;
	// long diskSumSize = 0;
	// long diskUsedSize = 0;
	// int containerSum = 0;
	// String url = "/" + SysConstants.URL_MANAGE_VERSION + "/hosts?cluster=" +
	// cluster.getRelateId();
	// RespJson httpRespJson = sendHttpGet(siteId, SysConstants.URL_TYPE_MANAGE,
	// url);
	// if (httpRespJson.getStatus() != HttpStatus.SC_OK) {
	// throw new APIException(httpRespJson.getMsg());
	// }
	//
	// JSONArray resJsonArray = (JSONArray) httpRespJson.getData();
	// for (int i = 0; i < resJsonArray.size(); i++) {
	// JSONObject hostJsonObj = resJsonArray.getJSONObject(i);
	// JSONObject engineJson = hostJsonObj.getJSONObject("Engine");
	// cpuSum += engineJson.getIntValue("cpus");
	// cpuUsed += (engineJson.getIntValue("cpus") -
	// engineJson.getLongValue("free_cpus"));
	// memSumSize += engineJson.getLongValue("memory");
	// memUsedSize += (engineJson.getLongValue("memory") -
	// engineJson.getLongValue("free_memory"));
	// JSONArray containerJsonArr = hostJsonObj.getJSONArray("containers");
	// if (containerJsonArr != null) {
	// containerSum += containerJsonArr.size();
	// }
	// JSONArray volumeJsonArr = hostJsonObj.getJSONArray("volume_drivers");
	// if (volumeJsonArr != null) {
	// for (int j = 0; j < volumeJsonArr.size(); j++) {
	// JSONObject volumeJsonObj = volumeJsonArr.getJSONObject(j);
	// if (volumeJsonObj.getString("type").equals("local:HDD")) {
	// diskSumSize += volumeJsonObj.getLongValue("total");
	// diskUsedSize += (volumeJsonObj.getLongValue("total") -
	// volumeJsonObj.getLongValue("free"));
	// }
	// }
	// }
	// }
	// cpuJson.put("cpuSum", cpuSum);
	// cpuJson.put("cpuUsed", cpuUsed);
	// memJson.put("memSumSize", memSumSize);
	// memJson.put("memUsedSize", memUsedSize);
	// diskJson.put("diskSumSize", diskSumSize);
	// diskJson.put("diskUsedSize", diskUsedSize);
	// containerJson.put("containerSum", containerSum);
	// return RespJsonFactory.buildOK(json);
	// } catch (Exception e) {
	// logger.error("集群资源分配查询异常", e);
	// throw new APIException("集群资源分配查询异常:" + e.getMessage());
	// }
	// }
	//
	// public RespJson getServStatus(HttpServletRequest request, Map<String,
	// Object> param) throws APIException {
	// try {
	// JSONObject json = new JSONObject();
	//
	// RespJson searchServRespJson = servService.list(param);
	// if (searchServRespJson.getStatus() == HttpStatus.SC_OK) {
	// @SuppressWarnings("unchecked")
	// List<ServDto> servs = (List<ServDto>) searchServRespJson.getData();
	// int passingCnt = 0;
	// int warningCnt = 0;
	// int criticalCnt = 0;
	// int unknownCnt = 0;
	// for (ServDto serv : servs) {
	// if (DictConstants.SERV_STATUS_PASSING.equals(serv.getStatus())) {
	// passingCnt++;
	// } else if (DictConstants.SERV_STATUS_WARNNING.equals(serv.getStatus())) {
	// warningCnt++;
	// } else if (DictConstants.SERV_STATUS_CRITICAL.equals(serv.getStatus())) {
	// criticalCnt++;
	// } else {
	// unknownCnt++;
	// }
	// }
	// json.put("passingCnt", passingCnt);
	// json.put("warningCnt", warningCnt);
	// json.put("criticalCnt", criticalCnt);
	// json.put("unknownCnt", unknownCnt);
	// }
	// return RespJsonFactory.buildOK(json);
	// } catch (Exception e) {
	// logger.error("服务状态查询异常", e);
	// throw new APIException("服务状态查询异常:" + e.getMessage());
	// }
	// }
	//
	// public RespJson getServResourcesAllocation(HttpServletRequest request,
	// Map<String, Object> param)
	// throws APIException {
	// try {
	// JSONObject json = new JSONObject();
	//
	// String servId = (String) param.get("servId");
	// ServEntity serv = servDao.getLess(servId);
	// if (serv != null) {
	// String siteId = serv.getArea().getSite().getId();
	// List<SubServEntity> subServs = serv.getSubServs();
	// if (subServs != null) {
	// Calendar now = Calendar.getInstance();
	// now.add(Calendar.MINUTE, -2);
	// now.set(Calendar.SECOND, 0);
	// long queryStartTimeSecs = now.getTimeInMillis() / 1000;
	// long queryEndTimeSecs = queryStartTimeSecs + 59;
	// double cpuUsageCnt = 0;
	// double memUsageCnt = 0;
	// int connectionCnt = 0;
	// int hitCnt = 0;
	// int unitCnt = 0;
	// for (SubServEntity subServ : subServs) {
	// String relateId = subServ.getRelateId();
	// String dfSubServId = subServ.getDefinitionSubServ().getId();
	// DefinitionMetricEntity definitionMetric = definitionMetricCache
	// .getDfMetricFromCache(dfSubServId, MetricConstants.CPU_USAGE);
	// String cpuUsageUrl = "/" + SysConstants.URL_MONITOR_VERSION +
	// "/unit/container?tag=" + relateId
	// + "&metric=" + definitionMetric.getValue() + "&start_time=" +
	// queryStartTimeSecs
	// + "&end_time=" + queryEndTimeSecs;
	// RespJson cpuUsageHttpRespJson = sendHttpGet(siteId,
	// SysConstants.URL_TYPE_MONITOR, cpuUsageUrl);
	// if (cpuUsageHttpRespJson.getStatus() == HttpStatus.SC_OK) {
	// JSONArray cpuUsageResJsonArr = (JSONArray)
	// cpuUsageHttpRespJson.getData();
	// if (cpuUsageResJsonArr != null) {
	// if (unitCnt == 0) {
	// unitCnt += cpuUsageResJsonArr.size();
	// }
	// for (int j = 0; j < cpuUsageResJsonArr.size(); j++) {
	// cpuUsageCnt +=
	// cpuUsageResJsonArr.getJSONObject(j).getDoubleValue("value");
	// }
	// }
	// } else {
	// logger.error("CPU使用率调用接口异常：" + cpuUsageHttpRespJson.getMsg());
	// }
	//
	// definitionMetric =
	// definitionMetricCache.getDfMetricFromCache(dfSubServId,
	// MetricConstants.MEM_USAGE);
	// String memUsageUrl = "/" + SysConstants.URL_MONITOR_VERSION +
	// "/unit/container?tag=" + relateId
	// + "&metric=" + definitionMetric.getValue() + "&start_time=" +
	// queryStartTimeSecs
	// + "&end_time=" + queryEndTimeSecs;
	// RespJson memUsageHttpRespJson = sendHttpGet(siteId,
	// SysConstants.URL_TYPE_MONITOR, memUsageUrl);
	// if (memUsageHttpRespJson.getStatus() == HttpStatus.SC_OK) {
	// JSONArray memUsageResJsonArr = (JSONArray)
	// memUsageHttpRespJson.getData();
	// if (memUsageResJsonArr != null) {
	// if (unitCnt == 0) {
	// unitCnt += memUsageResJsonArr.size();
	// }
	// for (int j = 0; j < memUsageResJsonArr.size(); j++) {
	// memUsageCnt +=
	// memUsageResJsonArr.getJSONObject(j).getDoubleValue("value");
	// }
	// }
	// } else {
	// logger.error("内存使用率调用接口异常：" + memUsageHttpRespJson.getMsg());
	// }
	//
	// definitionMetric =
	// definitionMetricCache.getDfMetricFromCache(dfSubServId,
	// MetricConstants.CONNECTION);
	// String connectionUrl = "/" + SysConstants.URL_MONITOR_VERSION +
	// "/units?tag=" + relateId
	// + "&metric=" + definitionMetric.getValue() + "&start_time=" +
	// queryStartTimeSecs
	// + "&end_time=" + queryEndTimeSecs;
	// RespJson connectionHttpRespJson = sendHttpGet(siteId,
	// SysConstants.URL_TYPE_MONITOR,
	// connectionUrl);
	// if (connectionHttpRespJson.getStatus() == HttpStatus.SC_OK) {
	// JSONArray connectionResJsonArr = (JSONArray)
	// connectionHttpRespJson.getData();
	// if (connectionResJsonArr != null) {
	// if (unitCnt == 0) {
	// unitCnt += connectionResJsonArr.size();
	// }
	// for (int j = 0; j < connectionResJsonArr.size(); j++) {
	// connectionCnt +=
	// connectionResJsonArr.getJSONObject(j).getDoubleValue("value");
	// }
	// }
	// } else {
	// logger.error("连接数调用接口异常：" + connectionHttpRespJson.getMsg());
	// }
	//
	// definitionMetric =
	// definitionMetricCache.getDfMetricFromCache(dfSubServId,
	// MetricConstants.HIT);
	// String hitUrl = "/" + SysConstants.URL_MONITOR_VERSION + "/units?tag=" +
	// relateId + "&metric="
	// + definitionMetric.getValue() + "&start_time=" + queryStartTimeSecs +
	// "&end_time="
	// + queryEndTimeSecs;
	// RespJson hitHttpRespJson = sendHttpGet(siteId,
	// SysConstants.URL_TYPE_MONITOR, hitUrl);
	// if (hitHttpRespJson.getStatus() == HttpStatus.SC_OK) {
	// JSONArray hitResJsonArr = (JSONArray) hitHttpRespJson.getData();
	// if (hitResJsonArr != null) {
	// if (unitCnt == 0) {
	// unitCnt += hitResJsonArr.size();
	// }
	// for (int j = 0; j < hitResJsonArr.size(); j++) {
	// hitCnt += hitResJsonArr.getJSONObject(j).getDoubleValue("value");
	// }
	// }
	// } else {
	// logger.error("命中次数调用接口异常：" + hitHttpRespJson.getMsg());
	// }
	// }
	//
	// double cpuUsageAvg = 0;
	// double memUsageAvg = 0;
	// int hitAvg = 0;
	// if (unitCnt != 0) {
	// cpuUsageAvg = NumberUtils.retainDigits(cpuUsageCnt / unitCnt);
	// memUsageAvg = NumberUtils.retainDigits(memUsageCnt / unitCnt);
	// hitAvg = hitCnt / unitCnt;
	// }
	// json.put("cpuUsage", cpuUsageAvg);
	// json.put("memUsage", memUsageAvg);
	// json.put("hit", hitAvg);
	// json.put("connection", connectionCnt);
	// }
	// }
	// return RespJsonFactory.buildOK(json);
	// } catch (Exception e) {
	// logger.error("服务资源分配查询异常", e);
	// throw new APIException("服务资源分配查询异常:" + e.getMessage());
	// }
	// }
	//
	// public RespJson getServOpsOrQps(HttpServletRequest request, Map<String,
	// Object> param) throws APIException {
	// try {
	// String servId = (String) param.get("servId");
	// ServEntity serv = servDao.getLess(servId);
	// if (serv != null) {
	// String definitionServId = serv.getDefinitionServ().getId();
	// if (definitionServId.equals("df_serv_mysql")) {
	// return getMySqlOps(request, param);
	// } else if (definitionServId.equals("df_serv_redis")) {
	// return getRedisQps(request, param);
	// }
	// }
	// return RespJsonFactory.build(HttpStatus.SC_GONE, "服务不存在");
	// } catch (Exception e) {
	// logger.error("服务QPS/OPS查询异常", e);
	// throw new APIException("服务QPS/OPS查询异常:" + e.getMessage());
	// }
	// }
	//
	// private RespJson getMySqlOps(HttpServletRequest request, Map<String,
	// Object> param) throws APIException {
	// try {
	// JSONObject json = new JSONObject();
	// Calendar now = Calendar.getInstance();
	// now.add(Calendar.HOUR_OF_DAY, -6);
	// now.set(Calendar.SECOND, 0);
	// int hour = 6;
	// long queryStartTimeSecs = now.getTimeInMillis() / 1000;
	// String servId = (String) param.get("servId");
	// ServEntity serv = servDao.getLess(servId);
	// List<JSONObject> ops_selects = listMySqlOps_select(request, serv,
	// queryStartTimeSecs, hour);
	// List<JSONObject> ops_inserts = listMySqlOps_insert(request, serv,
	// queryStartTimeSecs, hour);
	// List<JSONObject> ops_updates = listMySqlOps_update(request, serv,
	// queryStartTimeSecs, hour);
	// List<JSONObject> ops_deletes = listMySqlOps_delete(request, serv,
	// queryStartTimeSecs, hour);
	// json.put("ops_select", ops_selects);
	// json.put("ops_insert", ops_inserts);
	// json.put("ops_update", ops_updates);
	// json.put("ops_delete", ops_deletes);
	// return RespJsonFactory.buildOK(json);
	// } catch (Exception e) {
	// logger.error("服务OPS查询异常", e);
	// throw new APIException("服务OPS查询异常:" + e.getMessage());
	// }
	// }
	//
	// private List<JSONObject> listMySqlOps_select(HttpServletRequest request,
	// ServEntity serv, long queryStartTimeSecs,
	// int hour) {
	// List<JSONObject> ops_selects = new ArrayList<JSONObject>(hour * 60);
	// try {
	// String siteId = serv.getArea().getSite().getId();
	// List<SubServEntity> subServs = serv.getSubServs();
	// if (subServs != null) {
	// List<JSONObject> unitOps_selects = new ArrayList<JSONObject>();
	// for (SubServEntity subServ : subServs) {
	// String relateId = subServ.getRelateId();
	// String dfSubServId = subServ.getDefinitionSubServ().getId();
	// DefinitionMetricEntity definitionMetric_ops_select =
	// definitionMetricCache
	// .getDfMetricFromCache(dfSubServId, MetricConstants.OPS_SELECT);
	// long queryEndTimeSecs = queryStartTimeSecs + hour * 60 * 60;
	// String ops_selectUrl = "/" + SysConstants.URL_MONITOR_VERSION +
	// "/units?tag=" + relateId
	// + "&metric=" + definitionMetric_ops_select.getValue() + "&start_time=" +
	// queryStartTimeSecs
	// + "&end_time=" + queryEndTimeSecs;
	// RespJson ops_selectHttpRespJson = sendHttpGet(siteId,
	// SysConstants.URL_TYPE_MONITOR, ops_selectUrl);
	// if (ops_selectHttpRespJson.getStatus() == HttpStatus.SC_OK) {
	// JSONArray ops_selectResJsonArr = (JSONArray)
	// ops_selectHttpRespJson.getData();
	// if (ops_selectResJsonArr != null) {
	// for (int j = 0; j < ops_selectResJsonArr.size(); j++) {
	// unitOps_selects.add(ops_selectResJsonArr.getJSONObject(j));
	// }
	// }
	// } else {
	// logger.error("服务OPS_SELECT查询异常:" + ops_selectHttpRespJson.getMsg());
	// }
	//
	// for (int m = 0; m <= hour * 60; m++) {
	// JSONObject ops_selectJson = new JSONObject();
	// ops_selectJson.put("timestamp", (queryStartTimeSecs + m * 60) * 1000);
	//
	// int qpsSum = 0;
	// for (JSONObject unitOps : unitOps_selects) {
	// if (unitOps.getLongValue("timestamp") / 60 * 60 == queryStartTimeSecs + m
	// * 60) {
	// qpsSum += unitOps.getIntValue("value");
	// }
	// }
	// ops_selectJson.put("value", qpsSum);
	// ops_selects.add(ops_selectJson);
	// }
	// }
	// }
	// } catch (Exception e) {
	// logger.error("服务OPS_SELECT查询异常", e);
	// }
	// return ops_selects;
	// }
	//
	// private List<JSONObject> listMySqlOps_insert(HttpServletRequest request,
	// ServEntity serv, long queryStartTimeSecs,
	// int hour) {
	// List<JSONObject> ops_inserts = new ArrayList<JSONObject>(hour * 60);
	// try {
	// String siteId = serv.getArea().getSite().getId();
	// List<SubServEntity> subServs = serv.getSubServs();
	// if (subServs != null) {
	// List<JSONObject> unitOps_inserts = new ArrayList<JSONObject>();
	// for (SubServEntity subServ : subServs) {
	// String relateId = subServ.getRelateId();
	// String dfSubServId = subServ.getDefinitionSubServ().getId();
	// DefinitionMetricEntity definitionMetric_ops_insert =
	// definitionMetricCache
	// .getDfMetricFromCache(dfSubServId, MetricConstants.OPS_INSERT);
	// long queryEndTimeSecs = queryStartTimeSecs + hour * 60 * 60;
	// String ops_insertUrl = "/" + SysConstants.URL_MONITOR_VERSION +
	// "/units?tag=" + relateId
	// + "&metric=" + definitionMetric_ops_insert.getValue() + "&start_time=" +
	// queryStartTimeSecs
	// + "&end_time=" + queryEndTimeSecs;
	// RespJson ops_insertHttpRespJson = sendHttpGet(siteId,
	// SysConstants.URL_TYPE_MONITOR, ops_insertUrl);
	// if (ops_insertHttpRespJson.getStatus() == HttpStatus.SC_OK) {
	// JSONArray ops_insertResJsonArr = (JSONArray)
	// ops_insertHttpRespJson.getData();
	// if (ops_insertResJsonArr != null) {
	// for (int j = 0; j < ops_insertResJsonArr.size(); j++) {
	// unitOps_inserts.add(ops_insertResJsonArr.getJSONObject(j));
	// }
	// }
	// } else {
	// logger.error("服务OPS_SELECT查询异常:" + ops_insertHttpRespJson.getMsg());
	// }
	//
	// for (int m = 0; m <= hour * 60; m++) {
	// JSONObject ops_insertJson = new JSONObject();
	// ops_insertJson.put("timestamp", (queryStartTimeSecs + m * 60) * 1000);
	//
	// int qpsSum = 0;
	// for (JSONObject unitOps : unitOps_inserts) {
	// if (unitOps.getLongValue("timestamp") / 60 * 60 == queryStartTimeSecs + m
	// * 60) {
	// qpsSum += unitOps.getIntValue("value");
	// }
	// }
	// ops_insertJson.put("value", qpsSum);
	// ops_inserts.add(ops_insertJson);
	// }
	// }
	// }
	// } catch (Exception e) {
	// logger.error("服务OPS_INSERT查询异常", e);
	// }
	// return ops_inserts;
	// }
	//
	// private List<JSONObject> listMySqlOps_update(HttpServletRequest request,
	// ServEntity serv, long queryStartTimeSecs,
	// int hour) {
	// List<JSONObject> ops_updates = new ArrayList<JSONObject>(hour * 60);
	// try {
	// String siteId = serv.getArea().getSite().getId();
	// List<SubServEntity> subServs = serv.getSubServs();
	// if (subServs != null) {
	// List<JSONObject> unitOps_updates = new ArrayList<JSONObject>();
	// for (SubServEntity subServ : subServs) {
	// String relateId = subServ.getRelateId();
	// String dfSubServId = subServ.getDefinitionSubServ().getId();
	// DefinitionMetricEntity definitionMetric_ops_update =
	// definitionMetricCache
	// .getDfMetricFromCache(dfSubServId, MetricConstants.OPS_UPDATE);
	// long queryEndTimeSecs = queryStartTimeSecs + hour * 60 * 60;
	// String ops_updateUrl = "/" + SysConstants.URL_MONITOR_VERSION +
	// "/units?tag=" + relateId
	// + "&metric=" + definitionMetric_ops_update.getValue() + "&start_time=" +
	// queryStartTimeSecs
	// + "&end_time=" + queryEndTimeSecs;
	// RespJson ops_updateHttpRespJson = sendHttpGet(siteId,
	// SysConstants.URL_TYPE_MONITOR, ops_updateUrl);
	// if (ops_updateHttpRespJson.getStatus() == HttpStatus.SC_OK) {
	// JSONArray ops_updateResJsonArr = (JSONArray)
	// ops_updateHttpRespJson.getData();
	// if (ops_updateResJsonArr != null) {
	// for (int j = 0; j < ops_updateResJsonArr.size(); j++) {
	// unitOps_updates.add(ops_updateResJsonArr.getJSONObject(j));
	// }
	// }
	// } else {
	// logger.error("服务OPS_SELECT查询异常:" + ops_updateHttpRespJson.getMsg());
	// }
	//
	// for (int m = 0; m <= hour * 60; m++) {
	// JSONObject ops_updateJson = new JSONObject();
	// ops_updateJson.put("timestamp", (queryStartTimeSecs + m * 60) * 1000);
	//
	// int qpsSum = 0;
	// for (JSONObject unitOps : unitOps_updates) {
	// if (unitOps.getLongValue("timestamp") / 60 * 60 == queryStartTimeSecs + m
	// * 60) {
	// qpsSum += unitOps.getIntValue("value");
	// }
	// }
	// ops_updateJson.put("value", qpsSum);
	// ops_updates.add(ops_updateJson);
	// }
	// }
	// }
	// } catch (Exception e) {
	// logger.error("服务OPS_UPDATE查询异常", e);
	// }
	// return ops_updates;
	// }
	//
	// private List<JSONObject> listMySqlOps_delete(HttpServletRequest request,
	// ServEntity serv, long queryStartTimeSecs,
	// int hour) {
	// List<JSONObject> ops_deletes = new ArrayList<JSONObject>(hour * 60);
	// try {
	// String siteId = serv.getArea().getSite().getId();
	// List<SubServEntity> subServs = serv.getSubServs();
	// if (subServs != null) {
	// List<JSONObject> unitOps_deletes = new ArrayList<JSONObject>();
	// for (SubServEntity subServ : subServs) {
	// String relateId = subServ.getRelateId();
	// String dfSubServId = subServ.getDefinitionSubServ().getId();
	// DefinitionMetricEntity definitionMetric_ops_delete =
	// definitionMetricCache
	// .getDfMetricFromCache(dfSubServId, MetricConstants.OPS_DELETE);
	// long queryEndTimeSecs = queryStartTimeSecs + hour * 60 * 60;
	// String ops_deleteUrl = "/" + SysConstants.URL_MONITOR_VERSION +
	// "/units?tag=" + relateId
	// + "&metric=" + definitionMetric_ops_delete.getValue() + "&start_time=" +
	// queryStartTimeSecs
	// + "&end_time=" + queryEndTimeSecs;
	// RespJson ops_deleteHttpRespJson = sendHttpGet(siteId,
	// SysConstants.URL_TYPE_MONITOR, ops_deleteUrl);
	// if (ops_deleteHttpRespJson.getStatus() == HttpStatus.SC_OK) {
	// JSONArray ops_deleteResJsonArr = (JSONArray)
	// ops_deleteHttpRespJson.getData();
	// if (ops_deleteResJsonArr != null) {
	// for (int j = 0; j < ops_deleteResJsonArr.size(); j++) {
	// unitOps_deletes.add(ops_deleteResJsonArr.getJSONObject(j));
	// }
	// }
	// } else {
	// logger.error("服务OPS_SELECT查询异常:" + ops_deleteHttpRespJson.getMsg());
	// }
	//
	// for (int m = 0; m <= hour * 60; m++) {
	// JSONObject ops_deleteJson = new JSONObject();
	// ops_deleteJson.put("timestamp", (queryStartTimeSecs + m * 60) * 1000);
	//
	// int qpsSum = 0;
	// for (JSONObject unitOps : unitOps_deletes) {
	// if (unitOps.getLongValue("timestamp") / 60 * 60 == queryStartTimeSecs + m
	// * 60) {
	// qpsSum += unitOps.getIntValue("value");
	// }
	// }
	// ops_deleteJson.put("value", qpsSum);
	// ops_deletes.add(ops_deleteJson);
	// }
	// }
	// }
	// } catch (Exception e) {
	// logger.error("服务OPS_DELETE查询异常", e);
	// }
	// return ops_deletes;
	// }
	//
	// private RespJson getRedisQps(HttpServletRequest request, Map<String,
	// Object> param) throws APIException {
	// try {
	// JSONObject json = new JSONObject();
	// List<JSONObject> qpss = new ArrayList<JSONObject>(6 * 60);
	// String servId = (String) param.get("servId");
	// ServEntity serv = servDao.getLess(servId);
	// if (serv != null) {
	// String siteId = serv.getArea().getSite().getId();
	// List<SubServEntity> subServs = serv.getSubServs();
	// if (subServs != null) {
	// Calendar now = Calendar.getInstance();
	// now.add(Calendar.HOUR_OF_DAY, -6);
	// now.set(Calendar.SECOND, 0);
	// long queryStartTimeSecs = now.getTimeInMillis() / 1000;
	// long queryEndTimeSecs = queryStartTimeSecs + 6 * 60 * 60;
	// int unitCnt = 0;
	// List<JSONObject> unitOpss = new ArrayList<JSONObject>();
	// for (SubServEntity subServ : subServs) {
	// String relateId = subServ.getRelateId();
	// String dfSubServId = subServ.getDefinitionSubServ().getId();
	// DefinitionMetricEntity definitionMetric = definitionMetricCache
	// .getDfMetricFromCache(dfSubServId, MetricConstants.QPS);
	// String qpsUrl = "/" + SysConstants.URL_MONITOR_VERSION + "/units?tag=" +
	// relateId + "&metric="
	// + definitionMetric.getValue() + "&start_time=" + queryStartTimeSecs +
	// "&end_time="
	// + queryEndTimeSecs;
	// RespJson qpsHttpRespJson = sendHttpGet(siteId,
	// SysConstants.URL_TYPE_MONITOR, qpsUrl);
	// if (qpsHttpRespJson.getStatus() != HttpStatus.SC_OK) {
	// throw new APIException(qpsHttpRespJson.getMsg());
	// }
	// JSONArray qpsResJsonArr = (JSONArray) qpsHttpRespJson.getData();
	// if (qpsResJsonArr != null) {
	// List<String> unitIds = new ArrayList<String>();
	// for (int j = 0; j < qpsResJsonArr.size(); j++) {
	// String name = qpsResJsonArr.getJSONObject(j).getString("name");
	// if (!unitIds.contains(name)) {
	// unitIds.add(name);
	// }
	// }
	// unitCnt += unitIds.size();
	//
	// for (int j = 0; j < qpsResJsonArr.size(); j++) {
	// unitOpss.add(qpsResJsonArr.getJSONObject(j));
	// }
	// }
	// }
	//
	// for (int m = 0; m <= 6 * 60; m++) {
	// JSONObject qpsJson = new JSONObject();
	// qpsJson.put("timestamp", (queryStartTimeSecs + m * 60) * 1000);
	//
	// int qpsSum = 0;
	// int passingUnitCnt = 0;
	// for (JSONObject unitOps : unitOpss) {
	// if (unitOps.getLongValue("timestamp") / 60 * 60 == queryStartTimeSecs + m
	// * 60) {
	// qpsSum += unitOps.getIntValue("value");
	// passingUnitCnt++;
	// }
	// }
	// Integer value = null;
	// if (passingUnitCnt == unitCnt) {
	// if (unitCnt != 0) {
	// value = qpsSum / unitCnt;
	// }
	// }
	// qpsJson.put("value", value);
	// qpss.add(qpsJson);
	// }
	// }
	// }
	// json.put("qps", qpss);
	// return RespJsonFactory.buildOK(json);
	// } catch (Exception e) {
	// logger.error("服务QPS查询异常", e);
	// throw new APIException("服务QPS查询异常:" + e.getMessage());
	// }
	// }

}
